package com.linked.usermanage.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.linked.usermanage.user.bean.dto.UserAllInfoDTO;
import com.linked.usermanage.user.bean.dto.UserCountMonthDTO;
import com.linked.usermanage.user.bean.dto.UserRelatedTotalDTO;
import com.linked.usermanage.user.bean.param.UserAllInfoParam;
import com.linked.usermanage.user.bean.param.UserContainsRolesParam;
import com.linked.usermanage.user.bean.param.UserPageParam;
import com.linked.usermanage.user.bean.po.UserInfoPO;
import com.linked.usermanage.user.bean.po.UserRolesPO;
import com.linked.usermanage.user.mapper.IUserInfoMapper;
import com.linked.usermanage.user.service.IUserHandleService;
import com.linked.usermanage.user.mapper.IUserRolesMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

import java.util.stream.Collectors;

/**
 * @author :dbq
 * @date : 2022/10/21 14:38
 */
@Service
public class UserHandleServiceImpl implements IUserHandleService {

    private final static Logger logger = LoggerFactory.getLogger(UserHandleServiceImpl.class);

    private final IUserInfoMapper userInfoMapper;

    private final IUserRolesMapper userRolesMapper;


    @Autowired
    public UserHandleServiceImpl(IUserInfoMapper userInfoMapper, IUserRolesMapper userRolesMapper) {
        this.userInfoMapper = userInfoMapper;
        this.userRolesMapper = userRolesMapper;

    }

    @Override
    public boolean addAUser(UserInfoPO param) throws Exception {
        return userInfoMapper.insert(param) > 0;
    }

    @Override
    public IPage<UserInfoPO> queryUserPage(UserPageParam param) throws Exception {
        return userInfoMapper.queryUserPage(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public boolean addRolesToUser(UserContainsRolesParam param) throws Exception {
//        List<String> roleIds = param.getRoleIds();
//
//        if (!CollectionUtils.isEmpty(roleIds)) {
//            AtomicInteger ret = new AtomicInteger();
//            roleIds.stream().forEach(x -> {
//                UserRolesPO temp = new UserRolesPO();
//                temp.setRoleId(x);
//                temp.setUserId(param.getUserId());
//                ret.addAndGet(userRolesMapper.insert(temp));
//            });
//            if (ret.get() == roleIds.size()) {
//                return true;
//            }
//        }
        List<String> roleIds = param.getRoleIds();
        QueryWrapper<UserRolesPO> qw = new QueryWrapper<>();
        qw.eq("user_id", param.getUserId());
        List<UserRolesPO> userRolesPOS_old = userRolesMapper.selectList(qw);

        /**
         * 一、删除参数中没有，而数据库中存在的数据
         * */
        userRolesPOS_old.stream().forEach(x -> {
            if (!roleIds.contains(x.getRoleId())) {
                userRolesMapper.deleteById(x.getUserRoleId());
                if (logger.isInfoEnabled()) {
                    logger.info("解除用户-" + param.getUserId() + " 与 权限-" + x.getRoleId() + " 的关系");
                }
            }
        });
        /**
         * 二、新增参数中存在，而数据库中不存在的数据
         * */
        List<String> roleIds_old = userRolesPOS_old.stream().map(UserRolesPO::getRoleId).collect(Collectors.toList());
        roleIds.stream().forEach(x -> {
            if (CollectionUtils.isEmpty(roleIds_old) || !roleIds_old.contains(x)) {
                UserRolesPO temp = new UserRolesPO();
                temp.setRoleId(x);
                temp.setUserId(param.getUserId());
                userRolesMapper.insert(temp);
                if (logger.isInfoEnabled()) {
                    logger.info("绑定用户-" + param.getUserId() + " 与 权限-" + x + " 的关系");
                }
            }
        });
        return true;
    }

    @Override
    public UserAllInfoDTO getUserAllInfo(UserAllInfoParam param) throws Exception {

        UserAllInfoDTO ret = new UserAllInfoDTO();
        /**
         * 一、获取用户基本信息
         * */
        UserInfoPO infoTemp = userInfoMapper.selectById(param.getUserId());
        ret.setInfo(infoTemp);
        /**
         * 二、获取用户所有权限
         * */

        /**
         * 三、获取用户基本菜单
         * */


        return ret;
    }

    @Override
    public String queryUserIdByLoginId(String loginId) throws Exception {
        QueryWrapper<UserInfoPO> qw = new QueryWrapper<>();
        qw.eq("login_id", loginId);
        UserInfoPO temp = userInfoMapper.selectOne(qw);
        return temp.getUserId();
    }

    @Override
    public List<UserInfoPO> queryAllUserList() throws Exception {
        return userInfoMapper.queryAllUserList();
    }

    @Override
    public UserRelatedTotalDTO queryUserRelatedTotal() {
        return userInfoMapper.queryUserRelatedTotal();
    }

    @Override
    public List<UserCountMonthDTO> queryNewUserCountYear(String year) {
        return userInfoMapper.queryNewUserCountYear(year);
    }

    @Override
    public List<UserCountMonthDTO> queryUserLoginCountYear(String year) {
        return userInfoMapper.queryUserLoginCountYear(year);
    }

    @Override
    public UserInfoPO findUserInfo(String userId) {
        return userInfoMapper.selectById(userId);
    }
}
